#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import logging
import time
import datetime
import os
import oauth
import simplejson
import urllib
import random
from init import *
"""
    Template Path Genarete Class
"""
class TmplPath:
    def __init__(self, dir='/tmpl/'):
        self.dir = dir
        
    def GetTmplPath(self):
        return os.path.dirname(__file__) + self.dir
    
    def GetTmplFilePath(self, file):
        return os.path.join(self.GetTmplPath(), file)
    
class MainPage(webapp.RequestHandler):
    # Initilize Main Page
    def __init__(self):
        self.setting = {
            "CONSUMER_KEY" : '6LMfpjqrLx0x5IjB2aA7tg',
            "CONSUMER_SECRET_KEY":'ErWZIty5P4hxwQU90oDwpNR4MDbMDisZiJxdvQRbmIk',
            "ACCESS_TOKEN":'229879833-eAkxzHejloE8c4QrS95V2nMvVDEnPwCNeANhApof',
            "ACCESS_TOKEN_SECRET":'WOr3q8vRbVjcKQGQ8gDqoggnCfkVyTP6wUiHahHs'
        }
        # Template File Path
        self.tmpl = TmplPath().GetTmplFilePath('index.tmp');
    # 
    def TweetRequests(self, param=None, url='http://api.twitter.com/1/statuses/home_timeline.json', opt=None):
        client = oauth.TwitterClient(self.setting["CONSUMER_KEY"], self.setting["CONSUMER_SECRET_KEY"], None)
        if(param is None):
            return {"status_code":"500", "content":"Not Variable is Param"}
        """
            Get TL : Twitter
        """
        return client.make_request(url,
                            token=self.setting["ACCESS_TOKEN"],
                            secret=self.setting["ACCESS_TOKEN_SECRET"],
                            additional_params=param)   
    # Get Method
    def get(self):
        
        """
            Get : Home Timeline / Twitter
        """
        cookies = self.request.cookies
        param = {'q': '#boooobots', 'rpp':5}
        res = self.TweetRequests(url='http://search.twitter.com/search.json', param=param)
        json = simplejson.loads(res.content)
        self.response.headers['Content-Type'] = 'text/html;charset=utf-8'
        # 
        callback_url = "http://%s/callback" % (os.environ["HTTP_HOST"])
        client = oauth.TwitterClient(self.setting["CONSUMER_KEY"], self.setting["CONSUMER_SECRET_KEY"], callback_url)
        user_info={"login":False}
        message=""
        if cookies.get("tw_login"):
            user_info["login"]=True
            user_info["username"]=cookies.get("tw_username")
            user_info["pic"]=cookies.get("tw_picture")
            user_info["name"]=cookies.get("tw_name")
            user_info["service"]=cookies.get("tw_service")
            user_info["id"]=cookies.get("tw_id")
            """
                CallBack
                tw_username,tw_picture,tw_token,tw_token,tw_name,tw_service,tw_secret,tw_id,tw_login
                [Security]
                flag : tw_login / True | False
                access_token | access_token_secret :tw_token | tw_secret
            """
            w=u" #ブッッッヒャー #boooobots http://boooo-bot.appspot.com/"
            message=Bweet(word=w).Get()
            # self.response.out.write(len(message))
        else:
            pass
        #self.response.out.write(json)
        output = {"json":json,
                  "oauth_url":client.get_authorization_url(),
                  "login":user_info["login"],
                  "user_info":user_info,
                  "message":message
                  }
        
        self.response.out.write(template.render(self.tmpl, output))
    # Post Method    
    def post(self):
        (type,message) = (self.request.get("type"),self.request.get("status"))
        if type == "post":
            url = 'http://api.twitter.com/1/statuses/update.json'
            param={"status":message}
            cookies = self.request.cookies
            client = oauth.TwitterClient(self.setting["CONSUMER_KEY"], self.setting["CONSUMER_SECRET_KEY"], None)
            res = client.make_request(url,
                            token=cookies.get("tw_token"),
                            secret=cookies.get("tw_secret"),
                            additional_params=param,
                            method='POST')
            if res.status_code == 200:
                self.redirect("/")
            else:
                self.response.out.write("Status code:%s" % res.status_code)
        
class CallBackPage(webapp.RequestHandler):
    # Initilize Main Page
    def __init__(self):
        self.setting = {
            "CONSUMER_KEY" : '6LMfpjqrLx0x5IjB2aA7tg',
            "CONSUMER_SECRET_KEY":'ErWZIty5P4hxwQU90oDwpNR4MDbMDisZiJxdvQRbmIk',
            "ACCESS_TOKEN":'229879833-eAkxzHejloE8c4QrS95V2nMvVDEnPwCNeANhApof',
            "ACCESS_TOKEN_SECRET":'WOr3q8vRbVjcKQGQ8gDqoggnCfkVyTP6wUiHahHs'
        }
        # Template File Path
        # self.tmpl = TmplPath().GetTmplFilePath('index.tmp');
    def get(self):
        (oauth_token,oauth_verifier) = (self.request.get("oauth_token"), self.request.get("oauth_verifier"))
        if self.request.get("denied") is not "":
            #print self.request.get("denied")
            self.redirect("/");
            return False
        client = oauth.TwitterClient(self.setting["CONSUMER_KEY"], self.setting["CONSUMER_SECRET_KEY"], None)
        user_info = client.get_user_info(oauth_token, oauth_verifier)
        expires=900        
        for i in user_info:
            self.response.headers.add_header('Set-Cookie', '%s=%s; expires=%s' % ("tw_"+i, user_info[i], expires))
        """
            セキュリティ強化のため、Cookie保存からDataStore 保存
        """
        self.response.headers.add_header('Set-Cookie', '%s=%s; expires=%s' % ("tw_login", True, expires))
        self.redirect("/");

application = webapp.WSGIApplication([('/', MainPage),('/callback',CallBackPage)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
